import React, { useState } from 'react';
import { Input, Button, Row, Col, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import axios from 'axios';
const Login: React.FC = () => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    const { login } = useAuth();
    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!username || !password) {   
            message.error('请输入用户名和密码');
            return;
        }
        setLoading(true);
        try {
            const response = await axios.post('http://localhost:3003/api/auth/login', 
                { username, password },
                {
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    withCredentials: true
                }
            );
            if (response.data.success) {
                const { token, user } = response.data;
                login(token, user);
                message.success('登录成功');
                navigate('/form');
            } else {
                message.error(response.data.message || '登录失败');
            }
        } catch (error) {
            if (axios.isAxiosError(error)) {
                const errorMessage = error.response?.data?.message || '服务器连接失败';
                message.error(`登录失败: ${errorMessage}`);
                console.error('登录错误:', {
                    status: error.response?.status,
                    data: error.response?.data,
                    message: error.message
                });
            } else {
                message.error('登录失败: 未知错误');
                console.error('未知错误:', error);
            }
        } finally {
            setLoading(false);
        }
    };
    return (
        <div className="min-h-screen flex items-center justify-center bg-gray-50 p-8">
            <div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
                <h2 className="text-2xl font-bold text-gray-800 mb-6">登录</h2>
                <form onSubmit={handleSubmit}>
                    <Input
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        placeholder="用户名"
                        className="mb-4 w-full h-10 px-3 rounded-md border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all"
                    />
                    <Input.Password
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        placeholder="密码"
                        className="mb-4 w-full h-10 px-3 rounded-md border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition-all"
                    />
                    <Row gutter={8}>
                        <Col span={12}>
                            <Button 
                                type="primary" 
                                htmlType="submit" 
                                block 
                                className="w-full"
                                loading={loading}
                            >
                                登录
                            </Button>
                        </Col>
                        <Col span={12}>
                            <Button onClick={() => navigate('/register')} block className="w-full">
                                注册
                            </Button>
                        </Col>
                    </Row>
                </form>
            </div>
        </div>
    );
};

export default Login;